import React, { Component } from "react";
// 导入models
import models from "@/models/Goods";

import { Form, Modal, Button, message, Select, Input } from "antd";
import { PlusOutlined } from "@ant-design/icons";

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

const { Option } = Select;
class GoodsAdd extends Component {
  state = {
    // 数据
    data: [],
    visible: false,
    confirmLoading: false,
  };

  render() {
    return (
      <>
        <Button
          type="primary"
          size="small"
          onClick={this.showModal}
          icon={<PlusOutlined />}
        >
          新增
        </Button>
        <Modal
          title="Title"
          visible={this.state.visible}
          onOk={this.handleOk}
          confirmLoading={this.state.confirmLoading}
          onCancel={this.handleCancel}
          destroyOnClose={true}
        >
          <Form
            {...layout}
            name="basic"
            initialValues={{ remember: true }}
            onFinish={this.onFinish}
            onFinishFailed={this.onFinishFailed}
          >
            <Form.Item
              name="select"
              label="Select"
              hasFeedback
              rules={[
                { required: true, message: "Please select your country!" },
              ]}
            >
              <Select ref={(c) => (this.Sel = c)}>
                {this.state.data.map((item) => {
                  return (
                    <Option value={item._id}  key={item._id}>
                      {item.name}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>

            <Form.Item
              label="分类名称："
              name="name"
              rules={[{ required: true }]}
            >
              <Input ref={(c) => (this.inpText = c)} />
            </Form.Item>
          </Form>
        </Modal>
      </>
    );
  }

  // 显示模态框
  showModal = () => {
    this.setState({ visible: true });
    // 遍历数据，将每一项的name拿出来
    const itemList = [];
    this.props.data.forEach((item) => {
      itemList.push({ name: item.name, _id: item._id });
    });
    //  更新数据
    this.setState({ data: itemList });
  };

  // 点击确定
  handleOk = () => {
    if (this.Sel.props.value || this.inpText.props.value) {
		// 整合参数
		const obj = {
			categoryName: this.inpText.props.value,
			parentId:this.Sel.props.value
		}
		// 发起请求
		models.goodAdd(obj).then(ret => {
			if (ret.status === 0) {
				message.success("添加成功");
				this.props.show(this.props.page);
			}
		})
		// 关闭模态框
      this.setState({ visible: false, confirmLoading: false });
    } else {
      message.error("类名和分类不能为空!!!");
      this.setState({ confirmLoading: false });
    }
  };

  // 点击取消
  handleCancel = () => {
    this.setState({ visible: false });
  };
}

export default GoodsAdd;
